/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ListView;
import android.widget.Toast;

import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.alipay.Alipay;
import com.simon.mengkou.alipay.PayResult;
import com.simon.mengkou.data.bean.base.Address;
import com.simon.mengkou.data.bean.base.Niudan;
import com.simon.mengkou.data.bean.base.NiudanSKU;
import com.simon.mengkou.data.bean.base.Order;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.adapter.NDOrderAdapter;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/1/14.
 * desc    : 扭蛋订单界面
 */
public class NDOrderActivity extends BaseTopActivity
        implements Alipay.AlipayListener{
    //列表
    @Bind(R.id.order_id_list) ListView mLvOrders;

    private int mNum;
    private ArrayList<Niudan> mNiudans;
    private Order mOrder;
    private boolean mFlag;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        Intent intent = getIntent();
        if(intent != null) {
            mNiudans = (ArrayList<Niudan>) intent.getSerializableExtra(CstOuer.KEY.NIUDAN);
        }


        mOrder = new Order();

        if (UtilList.isNotEmpty(mNiudans)) {
            Product product = new Product();
            product.setTitle(mNiudans.get(0).getName());
            List<Product> goods = new ArrayList<>();
            goods.add(product);
            mOrder.setGoods(goods);

            float price = 0;
            for (Niudan niudan : mNiudans) {
                List<NiudanSKU> skus = niudan.getSku();
                for (NiudanSKU sku : skus) {
                    if (sku.isCheck()) {
                        mNum++;
                        price += niudan.getPrice();
                    }
                }
            }

            if(mNum <= 2) {
                price += 6;
            }

            mOrder.setAmount(price);
        }
    }

    @Override
    protected void initTop() {
        setNavigation(R.drawable.common_ic_left_nav);
        setTitle(R.string.order_title);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_order);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        NDOrderAdapter adapter = new NDOrderAdapter(this, mNiudans);
        mLvOrders.setAdapter(adapter);
    }

    /**
     * 提交订单
     */
    @OnClick(R.id.order_id_commit)
    protected void commit() {
        if(mNum > 0) {
            final Address addr = OuerApplication.mCacheFactory.getCache(DataCacheImpl.AddressDefaultCache.class,
                    OuerApplication.mUser.getUserId()).getData();
            if(addr == null) {
                OuerDispatcher.presentAddressManagerActivity(this);
            } else {
                if(mFlag) {
                    mOrder.setId(OuerApplication.mUser.getUserId() + System.currentTimeMillis());
//                    new Alipay(this).pay(mOrder, this);
                } else {
                    niudanSend();
                }
            }
        }
    }


    /**
     * 扭蛋寄送
     */
    private void niudanSend() {
        AgnettyFuture future = OuerApplication.mOuerFuture.niudanSend(
                OuerApplication.mUser.getUserId(), mNiudans,
                new OuerFutureListener(this) {
                    @Override
                    public void onStart(AgnettyResult result) {
                        super.onStart(result);
                        setWaitingDialog(true);
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        setWaitingDialog(false);
                        mFlag = (Boolean) result.getAttach();
                        if(mFlag) {
                            mOrder.setId(OuerApplication.mUser.getUserId() + System.currentTimeMillis());
//                            new Alipay(NDOrderActivity.this).pay(mOrder, NDOrderActivity.this);
                        } else {
                            UtilOuer.toast(NDOrderActivity.this, R.string.order_commit_failure);
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        setWaitingDialog(false);
                        UtilOuer.toast(NDOrderActivity.this, R.string.order_commit_failure);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        setWaitingDialog(false);
                    }
                });

        attachDestroyFutures(future);
    }


    @Override
    public void onResult(PayResult payResult) {
        String resultStatus = payResult.getResultStatus();

        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
        if (TextUtils.equals(resultStatus, "9000")) {
            Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
            niudanSend();
            finish();
        } else {
            // 判断resultStatus 为非“9000”则代表可能支付失败
            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            if (TextUtils.equals(resultStatus, "8000")) {
                Toast.makeText(this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                niudanSend();
                finish();
            } else {
                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();

            }
        }
    }
}
